<script lang="ts" setup>
import { ref, reactive, watch } from "vue"
import { type FormInstance, type FormRules, ElMessage, ElMessageBox } from "element-plus"
import { createTbForntApi, deleteTbFrontDataApi, updateTbFrontDataApi, getTbFrontDataApi } from "@/api/capture-tb/index"
import { usePagination } from "@/hooks/usePagination"
import { Search, Refresh } from "@element-plus/icons-vue"

const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()
const dialogVisible = ref(false)
const settingId = ref(false)
const tableData = ref()
defineOptions({
  name: "SettingPre"
})

// #region 渲染和查数据
const searchData = reactive({
  code: "",
  name: "",
  type: "tb"
})
const searchFormRef = ref<FormInstance | null>(null)
const tabledataApi = () => {
  getTbFrontDataApi({
    code: searchData.code || "",
    name: searchData.name || "",
    type: searchData.type,
    page: paginationData.currentPage,
    size: paginationData.pageSize
  }).then((res: any) => {
    tableData.value = res.data.list
    paginationData.total = res.data.total
  })
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    tabledataApi()
  }
  paginationData.currentPage = 1
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    tabledataApi()
  }
  paginationData.currentPage = 1
}
/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], tabledataApi, { immediate: true })
// #endregion

// #region 新增和修改
const settingApi = (row: any) => {
  dialogVisible.value = true
  console.log(row, "设置")
}
const settingIdApi = (row: any) => {
  dialogVisible.value = true
  settingId.value = true
  formData.data = row
}
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确认删除${row.name}？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteTbFrontDataApi(row.id).then(() => {
      ElMessage.success("删除成功")
      tabledataApi()
    })
  })
}
const settingtable = async () => {
  if (settingId.value == false) {
    dialogVisible.value = false
    await createTbForntApi(formData.data).then((res: any) => {
      if (res.code) {
        ElMessage.success(res.data)
        tabledataApi()
      }
    })
  } else {
    dialogVisible.value = false
    await updateTbFrontDataApi(formData.data).then((res: any) => {
      ElMessage.success(res.data)
      tabledataApi()
    })
  }
}
// #endregion

// #region 弹出框
const formData = reactive<any>({ data: {} })
const formRef = ref<FormInstance | null>(null)
const formRules: FormRules = reactive({
  code: [{ required: true, trigger: "blur", message: "请输入商品ID" }],
  name: [{ required: true, trigger: "blur", message: "请输入名字" }],
  minAge: [{ required: true, trigger: "blur", message: "请输入最小年龄" }],
  maxAge: [{ required: true, trigger: "blur", message: "请输入最大年龄" }]
})
const clearValidate = () => {
  formRef.value?.clearValidate()
}
const resetForm = () => {
  formData.data = {}
  settingId.value = false
  clearValidate()
}
const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      settingtable()
    } else {
      return false
    }
  })
}
// #endregion
</script>
<template>
  <div class="app-container">
    <el-card shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="code" label="商品ID">
          <el-input v-model.trim="searchData.code" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="name" label="名称">
          <el-input v-model.trim="searchData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="primary" @click="settingApi">校验配置</el-button>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData">
          <el-table-column prop="id" label="ID" width="120" align="center" />
          <el-table-column prop="code" label="商品ID" align="center" />
          <el-table-column prop="team" label="团队" align="center" />
          <el-table-column prop="name" label="名称" align="center" />
          <el-table-column prop="minAge" label="最小年龄" align="center" />
          <el-table-column prop="maxAge" label="最大年龄" align="center" />
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="settingIdApi(scope.row)">修改</el-button>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 弹出框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="settingId == false ? '添加信息' : '修改信息'"
      width="30%"
      @closed="resetForm"
    >
      <el-form ref="formRef" :model="formData.data" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="name" label="商品名字">
          <el-input v-model="formData.data.name" placeholder="请输入商品名字" />
        </el-form-item>
        <el-form-item prop="code" label="商品ID">
          <el-input v-model="formData.data.code" placeholder="请输入商品ID" />
        </el-form-item>

        <el-form-item prop="age" label="年龄限制">
          <el-input
            type="number"
            style="width: 46%"
            v-model="formData.data.minAge"
            placeholder="请输入最小年龄"
            oninput="if(value.length>2)value=value.slice(0, 2)"
          />
          <span style="display: inline-block; padding: 0 2%">至</span>
          <el-input
            type="number"
            style="width: 46%"
            v-model="formData.data.maxAge"
            placeholder="请输入最大年龄"
            oninput="if(value.length>2)value=value.slice(0, 2)"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}
.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.table-wrapper {
  margin-bottom: 20px;
}
.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
